﻿using Newtonsoft.Json;
using System;
using System.Configuration;
using System.Dynamic;
using System.Threading;
using System.Web;
using U8;
using System.Collections.Generic;
using System.Linq;
using System;
using System.Configuration;
using System.Dynamic;
using Interop.VoucherCO_SA;
using Interop.USSAServer;
using SaVoucherService;
using System.IO;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Reflection;
using System.Xml;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using MSXML2;
using U8SrvTrans;
using U8;
using U81;
using U82;



namespace WebApplication1
{
    /// <summary>
    /// Handler1 的摘要说明
    /// </summary>
    public class postCusPrice : IHttpHandler
    { 
        private static readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1); // 最大并发数设为1

        public static readonly string bz = ConfigurationManager.ConnectionStrings["conn1"].ConnectionString;

        public void ProcessRequest(HttpContext context)
        {
            _semaphore.Wait(); // 请求资源
            string authHeader = HttpContext.Current.Request.Headers["Authorization"];
            string bearerToken = authHeader.Substring("Bearer ".Length).Trim();
            PetaPoco.Database dbw = new PetaPoco.Database(bz);

            XZ_RZBfaModel RZB = new XZ_RZBfaModel();
            RZB.类型 = "调价单";
           // var connectionadd = new ADODB.Connection();
         //   RZB.类型 = "BOM";
            RZB.日期 = DateTime.Now;
            object jsonData = "";
            FileLogHelper.WriteTxtLog("调用开始", "11");
            dynamic jsonF = new ExpandoObject();  //动态MODEL 存DATE
            dynamic res = new ExpandoObject();  //动态MODEL 返回值
            res.msg = "";
            TokenModel model = dbw.FirstOrDefault<TokenModel>("select  * from  Token  where token=@token and  DATEDIFF(DAY,date, GETDATE())=0", new { token = bearerToken });
            if (model == null)
            {
                res.code = 401;
                res.msg = "密钥不合法或者已经过期";
                res.count = 0;
                jsonData = JsonConvert.SerializeObject(res);
                context.Response.Write(jsonData);
                _semaphore.Release(); // 释放资源

            }
            else
            {
                try
                {
                  
                    string name = "demo";
                    string pass = "";
                    String sSubId = "AS";
                    String sAccID = ConfigurationManager.AppSettings["ZTH"].ToString();
                    String sYear = DateTime.Now.Year.ToString();
                    String sDate = DateTime.Now.ToString("yyyy-MM-dd");
                    String sServer = ConfigurationManager.AppSettings["SERVER"].ToString();
                    String sUserID = name; ;
                    String sSerial = "";
                    U8Login.clsLogin u8Login = new U8Login.clsLogin();
                    if (!u8Login.Login(ref sSubId, ref sAccID, ref sYear, ref sUserID, ref pass, ref sDate, ref sServer, ref sSerial))
                    {
                        res.msg = u8Login.ShareString;
                        res.Code = "999";
                        return;
                    }

                 //   connectionadd.Open(u8Login.UfDbName);
                 //   connectionadd.BeginTrans();//事务开始


                    byte[] postData = new byte[context.Request.InputStream.Length];
                    context.Request.InputStream.Read(postData, 0, postData.Length);
                    string postDataString = System.Text.Encoding.UTF8.GetString(postData);
                    FileLogHelper.WriteTxtLog("调用开始", postDataString);
                    SA_CusPrice U8fa = JsonConvert.DeserializeObject<SA_CusPrice>(postDataString);
                    RZB.JSON = postDataString;
                    RZB.日期 = DateTime.Now;

                    dbw.Execute("delete SA_CusPriceJustMainView_temp");
                    dbw.Execute("delete SA_CusPriceJustDetailView_temp");



                    SA_CusPrice_tempModel mo = new SA_CusPrice_tempModel();

                    {
                        mo.ccode = U8fa.ccode;
                        mo.cdefine11 = U8fa.cdefine11;
                        mo.ddate = U8fa.ddate.ToString("yyyy-MM-dd");
                        string cdep = dbw.SingleOrDefault<string>("select  isnull(cDepCode,'')  cDepCode from Person  where cPersonCode='" + U8fa.cpersoncode + "'");
                        if (string.IsNullOrEmpty(cdep))
                        {
                            res.msg = "业务员编码不规范";
                            res.Code = "999";
                            RZB.错误内容= "业务员编码不规范";
                            RZB.是否成功 = "失败";
                            return;
                        }
                        mo.cpersoncode = U8fa.cpersoncode;
                        mo.cdepcode = cdep;
                        mo.ivouchstate = "Opening";
                        mo.id = 999;
                        dbw.Insert(mo);

                    }
                    int row = 1;
                    foreach (var m in U8fa.SA_CusPrice_Sub)
                    {

                        SA_CusPriceS_tempModel mos = new SA_CusPriceS_tempModel();
                        mos.cinvcode = m.cinvcode;
                        mos.ccuscode = m.ccuscode;
                        mos.cexch_name = "人民币";
                     
                        mos.iinvnowcost = m.iinvnowcost;
                        mos.icusdisrate = m.iinvnowcost;
                        mos.iinvscost= m.iinvnowcost;
                        mos.blimited = 1;
                        mos.iinvid = 1;
                        mos.blimitcus = 0;
                        mos.autoid = 999;

                        mos.dstartdate = DateTime.Now.Date;

                        string ccusccode = dbw.SingleOrDefault<string>("select  isnull(cCCCode,'')  cCCCode  from customer  where ccuscode='" + m.ccuscode + "'");

                        mos.operationtype = "新增";
                        mos.bsalepricefree1 = false;
                        mos.bsalepricefree2 = false;
                        mos.bsalepricefree3 = false;
                        mos.bsalepricefree4 = false;
                        mos.bsalepricefree5 = false;
                        mos.bsalepricefree6 = false;
                        mos.bsalepricefree7 = false;
                        mos.bsalepricefree8 = false;
                        mos.bsalepricefree9 = false;
                        mos.bsalepricefree10 = false;
                    

                        string pric = dbw.SingleOrDefault<string>("SELECT  max(ccuscode) ccuscode  FROM SA_CusUPrice where ccuscode='" + m.ccuscode+"'  and  cinvcode='"+m.cinvcode+"'  and  dStartDate= CONVERT(VARCHAR(10),'"+ mos.dstartdate+"', 120)");
                        if (!string.IsNullOrEmpty(pric))
                        {
                            mos.operationtype = "修改"; ;
                        }



                        if (string.IsNullOrEmpty(ccusccode))
                        {
                            res.msg = " 客户编码不规范";
                            res.Code = "999";
                            RZB.错误内容 = "客户编码不规范";
                            RZB.是否成功 = "失败";
                            return;
                        }
                        mos.ccusccode = ccusccode;

                        mos.irowno = row;
                        row++;
                        dbw.Insert(mos);
                    }




                    RZB.JSON = postDataString;
                    string errMsg = string.Empty;
                    string cCode = string.Empty;

                    //定义表头Dom对象
                    StringBuilder Strsql = new StringBuilder();
                    Strsql.Append("select bWireless='1',editprop='A',fornet='1','cvouchtype'='sa19',*   from SA_CusPriceJustMainView_temp");

                    MSXML2.DOMDocument domHead = getDom(Strsql.ToString(), u8Login.UfDbName);//生成表头DOM

                    Strsql = new StringBuilder();
                    Strsql.Append("select editprop='A',*  from  SA_CusPriceJustDetailView_temp");
                    MSXML2.DOMDocument domBody = getDom(Strsql.ToString(), u8Login.UfDbName);//生成表体DOM

                    Interop.USSAServer.clsSystem Cls = new Interop.USSAServer.clsSystem();;
                    //初始化CO
                    Cls.Init(u8Login);
                   
                    Cls.INIMyInfor();
                    Cls.bManualTrans = true;

                    Interop.VoucherCO_SA.ClsVoucherCO_SAClass Co = new Interop.VoucherCO_SA.ClsVoucherCO_SAClass();

                    Co.Init(Interop.VoucherCO_SA.VoucherTypeSA.SODetails, u8Login, null, "CS", Cls);
                    object curID = "";
                    string meg = Co.Save(domHead, domBody, 0, ref curID);
                    if (!string.IsNullOrEmpty(meg))
                    {
                        res.msg = "新增不成功" + meg;
                        res.Code = "999";
                        RZB.错误内容 = "新增不成功" + meg;
                        RZB.是否成功 = "失败";
                        return;
                    }


                    Strsql = new StringBuilder();
                    Strsql.Append("select 'cvouchtype'='sa19',*   from SA_CusPriceJustMainView where id=" + curID);
                    MSXML2.DOMDocument newdomHead = getDom(Strsql.ToString(), u8Login.UfDbName);//生成表头DOM


                    string Result1 = Co.VerifyVouch(newdomHead, true);
                    if (!string.IsNullOrEmpty(Result1))
                    {
                        res.msg = "审核不成功" + Result1;
                        res.Code = "999";
                        RZB.错误内容 = "审核不成功" + Result1;
                        RZB.是否成功 = "失败";
                        return;
                    }
                    RZB.返回ID = curID.ToString();
                    res.msg = "CO成功" ;
                    RZB.是否成功 = "成功";
                    res.Code = "200";
                 //   connectionadd.CommitTrans();

                }
                catch (Exception ee)
                {
                    RZB.是否成功 = "失败";
                    RZB.错误内容 = ee.Message; 
                    res.msg = ee.Message;

                    if (ee.Message.Length > 50)
                    {
                        res.msg = ee.Message.Substring(0, 50);
                    }
                    else
                    {
                        res.msg = ee.Message;
                    }
                    res.code = 999;

                   // connectionadd.RollbackTrans();//返回事务
                //    connectionadd.Close();  //关闭链接
                }//
                finally
                {
                    dbw.Save(RZB);
                    jsonData = JsonConvert.SerializeObject(res);
                    context.Response.ContentType = "application/json";
                    context.Response.Write(jsonData);
                    _semaphore.Release(); // 释放资源

                }
               
            
            }


  
        }




        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public string res(string ccode, string msg, string jsonData)
        {
            string resstr = "";


            return resstr;
        }

        public static MSXML2.DOMDocument getDom(string Strsql, string strConn)
        {
            MSXML2.DOMDocument dom = new MSXML2.DOMDocument();
            ADODB.Connection conn = new ADODB.Connection();
            ADODB.Recordset rs = new ADODB.Recordset();

            conn.Open(strConn);

            rs.Open(Strsql, conn, ADODB.CursorTypeEnum.adOpenForwardOnly, ADODB.LockTypeEnum.adLockOptimistic, -1);
            rs.Save(dom, ADODB.PersistFormatEnum.adPersistXML);

            return dom;
        }


    }
}